package com.jwdf.uda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.FragmentQqChangeUserNameBinding;
import com.jwdf.uda.event.IndividualEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.ChangeUserNameAction;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.ToastUtils;
import com.jwdf.uda.utils.UdaUtils;
import com.jwdf.uda.view.dialog.ConfirmDialog;

import retrofit2.Response;

/**
 * Created by Administrator on 2016/7/7.
 */
public class QQChangeUserNameActivity extends AbsTitleBarActivity {

    public static void start(Context context) {
        context.startActivity(new Intent(context, QQChangeUserNameActivity.class));
    }

    public static void start(Context context, String title) {
        Intent intent = new Intent(context, QQChangeUserNameActivity.class);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    @Override
    protected String getTopTitle() {
        String title = "用户名";
        if (getIntent().hasExtra("title")) {
            title = getIntent().getStringExtra("title");
        }
        return title;
    }

    @Override
    public void onHeadBackClick(View view) {
        UdaUtils.hideInputMethod(this, view);
        FragmentManager manager = getSupportFragmentManager();
        int count = manager.getBackStackEntryCount();
        if (count == 0) {
            doReset();
        } else {
            try {
                manager.popBackStackImmediate();
            } catch (IllegalStateException ignored) {
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            FragmentManager manager = getSupportFragmentManager();
            int count = manager.getBackStackEntryCount();
            if (count == 0) {
                doReset();
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    private void doReset() {
        ConfigUtils.removeCurrentUser(this);
        ConfigUtils.setHttpHeadersCookie(this, "");
        finish();
    }

    @Override
    protected BaseFragment onCreateContentFragment() {
        return new QQChangeUserNameFragment();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
    }

    @Override
    protected void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        if (!((QQChangeUserNameFragment) mFragment).isSucceed()) {
            ConfigUtils.removeCurrentUser(this);
            ConfigUtils.setHttpHeadersCookie(this, "");
        }
        super.onDestroy();
    }

    public void onEvent(IndividualEvent event) {
        finish();
    }

    public static class QQChangeUserNameFragment extends BaseFragment {
        private FragmentQqChangeUserNameBinding mDataBinding;
        private ConfirmDialog mChoiceDialog;
        private boolean mSucceed;
        private View.OnFocusChangeListener mInputFocusListener = new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (R.id.input_edit_user_name == v.getId()) {
                    if (!hasFocus) {
                        mDataBinding.ivClearUserNameInput.setVisibility(View.GONE);
                    } else {
                        if (mDataBinding.inputEditUserName.getText().toString().length() > 0) {
                            mDataBinding.ivClearUserNameInput.setVisibility(View.VISIBLE);
                        }
                    }
                } else if (R.id.input_edit_passwd == v.getId()) {
                    if (!hasFocus) {
                        mDataBinding.ivClearPasswdInput.setVisibility(View.GONE);
                    } else {
                        if (mDataBinding.inputEditPasswd.getText().toString().length() > 0) {
                            mDataBinding.ivClearPasswdInput.setVisibility(View.VISIBLE);
                        }
                    }
                } else if (R.id.input_edit_confirm_passwd == v.getId()) {
                    if (!hasFocus) {
                        mDataBinding.ivClearConfirmPasswdInput.setVisibility(View.GONE);
                    } else {
                        if (mDataBinding.inputEditConfirmPasswd.getText().toString().length() > 0) {
                            mDataBinding.ivClearConfirmPasswdInput.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        };

        private TextWatcher mUserTextChangeListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                mDataBinding.inputEditUserName.setSelection(s.length());
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mDataBinding.inputEditUserName.isFocused()) {
                    mDataBinding.ivClearUserNameInput.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
                }
                if (TextUtils.isEmpty(s)) {
                    mDataBinding.btnComleteInfo.setEnabled(false);
                } else {
                    mDataBinding.btnComleteInfo.setEnabled(true);
                }
            }
        };
        private TextWatcher mPassTextChangeListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //mDataBinding.inputEditPasswd.setSelection(s.length());
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mDataBinding.inputEditPasswd.isFocused()) {
                    mDataBinding.ivClearPasswdInput.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
                }
                if (TextUtils.isEmpty(s)) {
                    mDataBinding.btnComleteInfo.setEnabled(false);
                } else {
                    mDataBinding.btnComleteInfo.setEnabled(true);
                }
            }
        };
        private TextWatcher mConfirmPassTextChangeListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //mDataBinding.inputEditConfirmPasswd.setSelection(s.length());
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mDataBinding.inputEditConfirmPasswd.isFocused()) {
                    mDataBinding.ivClearConfirmPasswdInput.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
                }
                if (TextUtils.isEmpty(s)) {
                    mDataBinding.btnComleteInfo.setEnabled(false);
                } else {
                    mDataBinding.btnComleteInfo.setEnabled(true);
                }
            }
        };

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            mDataBinding = FragmentQqChangeUserNameBinding.inflate(inflater, container, false);
            initViews();
            return mDataBinding.getRoot();
        }

        private void initViews() {
            mDataBinding.btnComleteInfo.setOnClickListener(createOnClickListener());
            mDataBinding.inputEditUserName.addTextChangedListener(mUserTextChangeListener);
            mDataBinding.inputEditPasswd.addTextChangedListener(mPassTextChangeListener);
            mDataBinding.inputEditConfirmPasswd.addTextChangedListener(mConfirmPassTextChangeListener);
            mDataBinding.inputEditUserName.setOnFocusChangeListener(mInputFocusListener);
            mDataBinding.inputEditPasswd.setOnFocusChangeListener(mInputFocusListener);
            mDataBinding.inputEditConfirmPasswd.setOnFocusChangeListener(mInputFocusListener);
            mDataBinding.ivClearUserNameInput.setOnClickListener(createOnClickListener());
            mDataBinding.ivClearPasswdInput.setOnClickListener(createOnClickListener());
            mDataBinding.ivClearConfirmPasswdInput.setOnClickListener(createOnClickListener());
            mDataBinding.inputEditUserName.setFilters(new InputFilter[]{new InputFilter() {
                @Override
                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                    return UdaUtils.filterChinese(source.toString());
                }
            }});

        }

        private View.OnClickListener createOnClickListener() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UdaUtils.hideInputMethod(getContext(), mDataBinding.inputEditUserName);
                    if (R.id.btn_comlete_info == v.getId()) {
                        mDataBinding.ivClearUserNameInput.setVisibility(View.GONE);
                        mDataBinding.ivClearPasswdInput.setVisibility(View.GONE);
                        mDataBinding.ivClearConfirmPasswdInput.setVisibility(View.GONE);
                        String usrName = mDataBinding.inputEditUserName.getText().toString().trim();
                        String passwd = mDataBinding.inputEditPasswd.getText().toString().trim();
                        String confirmPasswd = mDataBinding.inputEditConfirmPasswd.getText().toString().trim();
                        if (TextUtils.isEmpty(usrName)) {
                            ToastUtils.show(getContext(), getString(R.string.user_can_not_be_null));
                            return;
                        }
                        if (TextUtils.isEmpty(passwd)) {
                            ToastUtils.show(getContext(), getString(R.string.pwd_can_not_be_null));
                            return;
                        }
                        if (passwd.length() < 6 || passwd.length() > 20) {
                            ToastUtils.show(getContext(), getString(R.string.pwd_can_not_be_length));
                            return;
                        }
                        if (TextUtils.isEmpty(confirmPasswd)) {
                            ToastUtils.show(getContext(), getString(R.string.confirm_pwd_can_not_be_null));
                            return;
                        }

                        if (!TextUtils.equals(passwd, confirmPasswd)) {
                            ToastUtils.show(getContext(), getString(R.string.twice_pwd_not_equal));
                            return;
                        }
                        showConfirmDialog(usrName, passwd);
                    } else if (R.id.iv_clear_user_name_input == v.getId()) {
                        mDataBinding.inputEditUserName.setText("");
                    } else if (R.id.iv_clear_passwd_input == v.getId()) {
                        mDataBinding.inputEditPasswd.setText("");
                    } else if (R.id.iv_clear_confirm_passwd_input == v.getId()) {
                        mDataBinding.inputEditConfirmPasswd.setText("");
                    }
                }
            };
        }

        public boolean isSucceed() {
            return mSucceed;
        }

        private void showConfirmDialog(final String usrName, final String passwd) {

            mChoiceDialog = new ConfirmDialog(getContext(), getString(R.string.dialog_set_passwd, usrName), getString(R.string.dialog_cancel), getString(R.string.dialog_sure), new ConfirmDialog.CallbackListener() {
                @Override
                public void clickNo() {
                }

                @Override
                public void clickYes() {
                    changeUserName(usrName, passwd);
                }
            });

            mChoiceDialog.show();
        }

        private void changeUserName(String usrName, String passwd) {
            showProgressDialog();
            onNewRequestCall(ChangeUserNameAction.newInstance(getContext(), usrName, passwd).request(new AHttpService.IResCallback<PbBean.PbResUserChangeUsername>() {
                @Override
                public void onCallback(int resultCode, Response<PbBean.PbResUserChangeUsername> response, PbBean.PbBaseServerInfo baseServerInfo) {
                    if (getView() != null) {
                        closeProgressDialog();
                        if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                            mSucceed = false;
                            return;
                        }
                        mSucceed = true;
                        getActivity().finish();
                        startActivityFromFragment(DefaultMainActivity.class);
                    }
                }
            }));
        }
    }
}
